package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.MemberInfoListMapper;
import cc.rengu.igas.momp.common.dao.impl.MemberInfoListMapperImpl;
import cc.rengu.igas.momp.common.entity.TMMemberDetail;
import cc.rengu.igas.momp.common.entity.TMMemberInfo;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.MembershipDetailInfoBean;
import cc.rengu.igas.momp.facade.request.QueryMemberDetailInfoRequest;
import cc.rengu.igas.momp.facade.response.QueryMemberDetailInfoResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : liujinan
 * @version 1.0.0
 * @date 2020/3/27
 * @Description: 会员明细查询功能实现
 */

public class MemberDetailInfoQueryService extends RadpService {

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {
            QueryMemberDetailInfoRequest queryMemberDetailInfoRequest = new QueryMemberDetailInfoRequest();
            ConvertUtil.convertOutput(queryMemberDetailInfoRequest);

            QueryMemberDetailInfoResponse queryMemberDetailInfoResponse = new QueryMemberDetailInfoResponse();
            queryMemberDetailInfoResponse.setHeader(queryMemberDetailInfoRequest.getHeader());
            BizResponse<QueryMemberDetailInfoResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryMemberDetailInfoResponse);

            // 服务调用
            BizResponse<QueryMemberDetailInfoResponse> bizResponseNew = memberDetailInfoQuery(xmlTreeUtil, queryMemberDetailInfoRequest, queryMemberDetailInfoResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
                xmlTreeUtil.setXmlTreeStringValue(CommonConstant.KEY_RESPDESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }

    private BizResponse<QueryMemberDetailInfoResponse> memberDetailInfoQuery(XmlTreeUtil xmlTreeUtil, QueryMemberDetailInfoRequest queryMemberDetailInfoRequest, QueryMemberDetailInfoResponse queryMemberDetailInfoResponse) throws Exception {

        BizResponse<QueryMemberDetailInfoResponse> bizResponse = new BizResponse<>();
        rglog.debug("TXN_NUM = {}", queryMemberDetailInfoRequest.getHeader().getTxnNum());

        String queryClause = queryMemberDetailInfoRequest.getHeader().getInstId() + queryMemberDetailInfoRequest.getMemberId();
        // 查询会员信息表数据
        TMMemberInfo tmMemberInfo = getMemberInfo(queryMemberDetailInfoRequest);

        if (null == tmMemberInfo) {
            rglog.error("根据查询条件查询会员信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }

        String mobileNo = tmMemberInfo.getMobileNo();
        String wechatOpenId = tmMemberInfo.getWechatOpenId();
        String alipayUserId = tmMemberInfo.getAlipayUserId();
        String cardNo = tmMemberInfo.getCardNo();

        List<MembershipDetailInfoBean> memberInfoDetailInfoList = new ArrayList<>();

        if (mobileNo != null) {
            //主手机号不为空，则设置为 0
            MembershipDetailInfoBean memberDetialInfoBean = new MembershipDetailInfoBean();
            memberDetialInfoBean.setMemberId(tmMemberInfo.getMemberId());
            memberDetialInfoBean.setMemberType(CommonConstant.MEMBERTYPE_IPHONE);
            memberDetialInfoBean.setUserId(mobileNo);
            //设置为主账号 0
            memberDetialInfoBean.setPrimaryAcctFlag(CommonConstant.ZERO_COMMON_CONSTANT);
            memberDetialInfoBean.setCreateType(tmMemberInfo.getImportMethod());
            memberDetialInfoBean.setCreateTime(tmMemberInfo.getImportDate());
            memberInfoDetailInfoList.add(memberDetialInfoBean);
        }
        if (wechatOpenId != null) {
            //微信OpenID不为空，则设置为 1
            MembershipDetailInfoBean memberDetialInfoBean = new MembershipDetailInfoBean();
            memberDetialInfoBean.setMemberId(tmMemberInfo.getMemberId());
            memberDetialInfoBean.setMemberType(CommonConstant.MEMBERTYPE_WX_OPENID);
            memberDetialInfoBean.setUserId(wechatOpenId);
            //设置为主账号 0
            memberDetialInfoBean.setPrimaryAcctFlag(CommonConstant.ZERO_COMMON_CONSTANT);
            memberDetialInfoBean.setCreateType(tmMemberInfo.getImportMethod());
            memberDetialInfoBean.setCreateTime(tmMemberInfo.getImportDate());
            memberInfoDetailInfoList.add(memberDetialInfoBean);
        }
        if (alipayUserId != null) {
            //支付宝UserID不为空，则设置为 2
            MembershipDetailInfoBean memberDetialInfoBean = new MembershipDetailInfoBean();
            memberDetialInfoBean.setMemberId(tmMemberInfo.getMemberId());
            memberDetialInfoBean.setMemberType(CommonConstant.MEMBERTYPE_ALI_USERID);
            memberDetialInfoBean.setUserId(alipayUserId);
            //设置为主账号 0
            memberDetialInfoBean.setPrimaryAcctFlag(CommonConstant.ZERO_COMMON_CONSTANT);
            memberDetialInfoBean.setCreateType(tmMemberInfo.getImportMethod());
            memberDetialInfoBean.setCreateTime(tmMemberInfo.getImportDate());
            memberInfoDetailInfoList.add(memberDetialInfoBean);
        }
        if (cardNo != null) {
            //本行银行卡号不为空，则设置为 3
            MembershipDetailInfoBean memberDetialInfoBean = new MembershipDetailInfoBean();
            memberDetialInfoBean.setMemberId(tmMemberInfo.getMemberId());
            memberDetialInfoBean.setMemberType(CommonConstant.MEMBERTYPE_CARDNO);
            memberDetialInfoBean.setUserId(cardNo);
            //设置为主账号 0
            memberDetialInfoBean.setPrimaryAcctFlag(CommonConstant.ZERO_COMMON_CONSTANT);
            memberDetialInfoBean.setCreateType(tmMemberInfo.getImportMethod());
            memberDetialInfoBean.setCreateTime(tmMemberInfo.getImportDate());
            memberInfoDetailInfoList.add(memberDetialInfoBean);
        }

        List<TMMemberDetail> memberDetailInfoList = new ArrayList<>();
        //查询会员详细信息表数据
        getMemberDetailInfo(queryMemberDetailInfoRequest, memberDetailInfoList);

        if (memberDetailInfoList.isEmpty()) {
            rglog.error("根据查询条件<{}>查询到0条详细会员详细信息（除主账号外无其他账号）!", queryClause);
            queryMemberDetailInfoResponse.setTotalRows(String.valueOf(memberInfoDetailInfoList.size()));
            List<MembershipDetailInfoBean> membershipDetailInfoList = new ArrayList<>();
            membershipDetailInfoList.addAll(memberInfoDetailInfoList);
            queryMemberDetailInfoResponse.setMemberDetailInfoList(membershipDetailInfoList);
        } else {
            //设置总记录数，非主账号+主账号
            queryMemberDetailInfoResponse.setTotalRows(String.valueOf(memberDetailInfoList.size() + memberInfoDetailInfoList.size()));
            //获取所有会员明细信息    无分页处理
            List<MembershipDetailInfoBean> membershipDetailInfo = memberDetailInfoList.stream().map(this::convertMembershipDetailInfoBean).collect(Collectors.toList());
            //将主账号信息加入
            membershipDetailInfo.addAll(memberInfoDetailInfoList);
            queryMemberDetailInfoResponse.setMemberDetailInfoList(membershipDetailInfo);
        }

        //设置总页数为1页
        queryMemberDetailInfoResponse.setTotalPage(CommonConstant.ONE_COMMON_CONSTANT);
        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryMemberDetailInfoResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryMemberDetailInfoResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        queryMemberDetailInfoResponse.setPageIndex(queryMemberDetailInfoRequest.getPageIndex());
        queryMemberDetailInfoResponse.setPageSize(queryMemberDetailInfoRequest.getPageSize());
        bizResponse.setResult(queryMemberDetailInfoResponse);

        return bizResponse;
    }

    /**
     * @param queryMemberDetailInfoRequest
     * @return void
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/30
     * @Description: 会员信息查询
     */
    private TMMemberInfo getMemberInfo(QueryMemberDetailInfoRequest queryMemberDetailInfoRequest) {

        try {
            String queryType = queryMemberDetailInfoRequest.getQueryType();
            rglog.info("查询类型queryType：" + queryType);
            MemberInfoListMapper membInfoListMapper = new MemberInfoListMapperImpl();
            //进行会员信息数据查询
            TMMemberInfo tmMemberInfo = membInfoListMapper.selectMemberInfoByPK(queryMemberDetailInfoRequest.getHeader().getInstId(),
                    queryMemberDetailInfoRequest.getMemberId());

            return tmMemberInfo;

        } catch (Exception e) {
            rglog.error("根据查询条件查询会员信息失败!");
            throw new BizException(RespCodeEnum.GET_MEMBERINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERINFO_ERROR.getRespDesc());
        }
    }

    /**
     * @param queryMemberDetailInfoRequest
     * @param memberDetailInfoList
     * @return void
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/30
     * @Description: 查询会员明细信息
     */

    private void getMemberDetailInfo(QueryMemberDetailInfoRequest queryMemberDetailInfoRequest, List<TMMemberDetail> memberDetailInfoList) {

        String queryClause = queryMemberDetailInfoRequest.getHeader().getInstId() + queryMemberDetailInfoRequest.getMemberId();
        try {
            MemberInfoListMapper mcInfoListMapper = new MemberInfoListMapperImpl();
            List<TMMemberDetail> objectList = mcInfoListMapper.selectMemberDetailInfoNoPage(queryMemberDetailInfoRequest.getHeader().getInstId(),
                    queryMemberDetailInfoRequest.getMemberId());
            if (null != objectList) {
                memberDetailInfoList.addAll(objectList);
            }
        } catch (Exception e) {
            rglog.error("根据查询条件<{}>获取会员明细信息(查询会员明细信息表)失败!", queryClause);
            throw new BizException(RespCodeEnum.GET_MEMBERDETAILINFO_ERROR.getRespCode(), RespCodeEnum.GET_MEMBERDETAILINFO_ERROR.getRespDesc());
        }
    }

    /**
     * @param mcMoneyOffInfo
     * @return cc.rengu.igas.momp.facade.bean.McInfo
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/3/27
     * @Description: 数据库实体类和接口实体类数据转换
     */
    private MembershipDetailInfoBean convertMembershipDetailInfoBean(TMMemberDetail memberDetailInfo) {
        MembershipDetailInfoBean membershipDetailInfo = new MembershipDetailInfoBean();
        try {
            //会员ID
            membershipDetailInfo.setMemberId(memberDetailInfo.getMemberId());
            //用户类型
            membershipDetailInfo.setMemberType(memberDetailInfo.getMemberType());
            //用户账号
            membershipDetailInfo.setUserId(memberDetailInfo.getUserId());
            //主账号标志 1非主账号
            membershipDetailInfo.setPrimaryAcctFlag(CommonConstant.ONE_COMMON_CONSTANT);
            //获取方式
            membershipDetailInfo.setCreateType(memberDetailInfo.getImportMethod());
            //获取时间
            membershipDetailInfo.setCreateTime(memberDetailInfo.getImportMethod());
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换会员详细信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        return membershipDetailInfo;
    }
}
